package me.jzn.alib.utils;

import android.app.Application;
import android.os.Build;

import androidx.annotation.RequiresApi;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.lang.reflect.Method;

import me.jzn.core.utils.CommUtil;
import me.jzn.core.utils.StrUtil;

public class ProcessUtil {
    public static String getProcessName() {
        if (Build.VERSION.SDK_INT >= 28) {
            return Application.getProcessName();
        }
        return getProcessName_3();
    }

    private static String getProcessName_1() {
        BufferedReader br = null;
        try {
            File file = new File("/proc/" + android.os.Process.myPid() + "/" + "cmdline");
            br = new BufferedReader(new FileReader(file));
            String processName = StrUtil.trim(br.readLine());
            return processName;
        } catch (Exception e) {
            Logger log = LoggerFactory.getLogger(ProcessUtil.class);
            log.warn("getProcessName_2 error:", e);
            return null;
        } finally {
            CommUtil.close(br);
        }
    }

//private static String getProcessName_2(Context ctx) {
//        return SysUtil.getProcessName(ctx);
//    }

    private static String getProcessName_3() {
        String processName = null;
        try {
            final Method declaredMethod = Class.forName("android.app.ActivityThread", false, ProcessUtil.class.getClassLoader())
                    .getDeclaredMethod("currentProcessName", (Class<?>[]) new Class[0]);
            declaredMethod.setAccessible(true);
            final Object invoke = declaredMethod.invoke(null, new Object[0]);
            if (invoke instanceof String) {
                processName = (String) invoke;
            }
        } catch (Throwable e) {
            Logger log = LoggerFactory.getLogger(ProcessUtil.class);
            log.warn("getProcessName_3 error:", e);
            return null;
        }
        return processName;
    }

    @RequiresApi(Build.VERSION_CODES.P)
    private String getProcessName_4() {
        return Application.getProcessName();
    }
}
